
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：历史出入金记录                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-04-08 14:38:39                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： History_CashChangesService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using BestTrader.Cms.ViewModels;
using AutoMapper;

namespace BestTrader.Cms.Services
{
    public class History_CashChangesService : IHistory_CashChangesService
    {
        private readonly IHistory_CashChangesRepository _repository;
        private readonly IManagerRepository _managerRepository;
        private readonly IManagerService _managerService;
        private readonly IManagerRoleService _managerRoleService;
        private readonly IMapper _mapper;

        public History_CashChangesService(
            IHistory_CashChangesRepository repository
          , IManagerRepository managerRepository
          , IMapper mapper
          , IManagerService managerService
          , IManagerRoleService managerRoleService
          )
        {
            _repository = repository;
            _managerRepository = managerRepository;
            _mapper = mapper;
            _managerService = managerService;
            _managerRoleService = managerRoleService;

        }
        /// <summary>
        /// </summary>
        /// <param name="model"></param>
        /// <param name="user"></param>
        /// <param name="role"></param>
        /// <returns></returns>

        public TableDataModel LoadData(HistoryCashRequestModel model, string user, string role)
        {
            var result = new TableDataModel();
            var UnitNames = new Dictionary<string, string>() { { "HKD", "HK" }, { "USD", "$" }, { "EUR", "€" }, { "JPY", "￥" }, { "CNY", "￥" }, { "RMB", "￥" }, { "AUD", "A$" } };

            string conditions = "where IsDelete=0 ";// 未删除的所有默认记录
            string Key = "";
            var manager = _managerService.GetManagerTableById(user);
            if (manager.Data == null || manager.Data?.RoleId.ToString() != role)
            {
                return result;
            }
            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $" and AccountName in(select UserName + '01' from Manager where RealName like @Key or UserName like @Key) ";
                Key = model.Key.ToSqlLikeParam();
            }
            conditions += GetConditions(model, user, role);

            var list = _repository.GetListPaged(model.Page, model.Limit, conditions, "Action_Time desc", new { Key = Key }).ToList();
            var viewList = new List<HistoryCashModel>();
            list.ForEach(x =>
            {
                var item = _mapper.Map<HistoryCashModel>(x);
                item.CurrencyCodeName = UnitNames[item.CurrencyCode];
                if (!item.AccountName.IsNullOrWhiteSpace())
                {
                    item.UserName = item.AccountName.Substring(0, item.AccountName.Length - 2);
                    item.RealName = _managerRepository.GetRealNameByUserName(item.UserName);
                }

                viewList.Add(item);
            });

            result.count = _repository.RecordCount(conditions, new { Key = Key });
            result.data = viewList;
            return result;
        }
        /// <summary>
        /// 获取筛选条件汇总
        /// </summary>
        /// <param name="model"></param>
        /// <param name="user"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        public TableDataModel GetTotalHistoryCashByConditions(HistoryCashRequestModel model, string user, string role)
        {
            var result = new TableDataModel()
            {
                data = new
                {
                    TotalInAmount = 0,
                    TotalInRMBAmount = 0,
                    TotalOutAmount = 0,
                    TotalOutRMBAmount = 0
                }
            };

            var UnitNames = new Dictionary<string, string>() { { "HKD", "HK" }, { "USD", "$" }, { "EUR", "€" }, { "JPY", "￥" }, { "CNY", "￥" }, { "RMB", "￥" }, { "AUD", "A$" } };

            string conditions = "where IsDelete=0 ";// 未删除的所有默认记录
            string Key = "";
            var manager = _managerService.GetManagerTableById(user);
            if (manager.Data == null || manager.Data?.RoleId.ToString() != role)
            {
                return result;
            }

            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $" and AccountName in(select UserName + '01' from Manager where RealName like @Key or UserName like @Key) ";
                Key = model.Key.ToSqlLikeParam();
            }
            conditions += GetConditions(model, user, role);

            var list = _repository.GetList(conditions, new { Key = Key }).ToList();

            var totalData = new
            {
                TotalInAmount = list.Where(p=>p.Cash_State==1).Sum(p=>p.Amount),
                TotalInRMBAmount = list.Where(p => p.Cash_State == 1).Sum(p => p.RMBAmount),
                TotalOutAmount = list.Where(p => p.Cash_State == 2).Sum(p => p.Amount),
                TotalOutRMBAmount = list.Where(p => p.Cash_State == 2).Sum(p => p.RMBAmount)
            };


            result.count = list.Count();
            result.data = totalData;
            return result;
        }

        public string GetConditions(HistoryCashRequestModel model, string user, string role)
        {
            string conditions = " ";// 

            var _managers = new List<ItemsDetailModel>();

            if (role != "3")
            {
                _managers = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(user, role, false);
                if (_managers.Any()) conditions += $" and AccountName in({ String.Join(',', _managers.Select(p => $"'{p.ItemName}01'")) }) ";
            }

            if (model.Start.HasValue)
            {
                conditions += $"and Action_Time >= '{ model.Start.Value }' ";
            }
            if (model.End.HasValue)
            {
                conditions += $"and Action_Time <= '{ model.End.Value.Date.AddDays(1).AddMinutes(-1) }' ";
            }
            if (model.State.HasValue)
            {
                conditions += $"and Cash_State = {model.State.Value} ";
            }
            if (model.ManagerId.HasValue)
            {
                var searchManager = _managerService.GetManagerTableById(model.ManagerId.ToString());
                if (searchManager.Data !=null) {
                  var subManager= _managerService.GetCacheSubManagerByUserId(searchManager.Data.Id.ToString(),searchManager.Data.RoleId.ToString());
                  if (subManager.Data.Any()) conditions += $" and AccountName in({ String.Join(',', subManager.Data.Select(p => $"'{p.UserName}01'")) }) ";
                }
            }
            return conditions;
        }



    }
}